package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.client.RedisClient;
import cn.itsource.hrm.service.IImageValidateCodeService;
import cn.itsource.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@Service
public class ImageValidateCodeServiceImpl implements IImageValidateCodeService {

    @Autowired
    private RedisClient redisClient;
    @Override
    public String generateImgCode(String key) {
        //1产生6随机字符
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2 写入redis
        Map<String,Object> params = new HashMap<>();
        params.put("key",key);
        params.put("value",code);
        params.put("expire",60);
        redisClient.add(params);
        //3 生成图片加密返回
        BASE64Encoder encoder = new BASE64Encoder();
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(100, 30, data, code);
        return encoder.encode(data.toByteArray());
    }
}
